<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { ElForm, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types/index'
import { localCache } from '@/utils/cache'
const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'
const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})
const rules: FormRules = {
  name: [
    { required: true, message: '不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{6,20}$/,
      message: '用户名长度在6-20位',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{3,}$/,
      message: '密码长度在3位以上',
      trigger: 'blur'
    }
  ]
}
// 执行帐号登录逻辑
// 验证输入的信息是否合规
const accountformRef = ref<InstanceType<typeof ElForm>>()
const useLogin = useLoginStore()
const accountLogin = (isRemember: boolean) => {
  if (accountformRef.value) {
    accountformRef.value.validate((valid, field) => {
      if (valid) {
        console.log('验证成功')
        // ElMessage({
        //   message: 'Congrats, this is a success message.',
        //   type: 'success'
        // })
        // 获取用户输入的帐号和密码
        const name = account.name
        const password = account.password
        // 向服务器发送网络请求（带帐号和密码）
        useLogin.loginAccountAction({ name, password }).then((res) => {
          // 判断是否需要记住密码
          if (isRemember) {
            localCache.setCache(CACHE_NAME, name)
            localCache.setCache(CACHE_PASSWORD, password)
          }
        })
      } else {
        console.log('验证失败', field)
        ElMessage({
          showClose: true,
          message: 'Oops, 请输入正确的帐号或密码.',
          type: 'error'
        })
      }
    })
  }

  // console.log('accountLogin', account.userName, account.userPwd)
}
defineExpose({
  accountLogin
})
</script>
<template>
  <div class="panel-account">
    <el-form
      :model="account"
      style="max-width: 460px"
      :rules="rules"
      status-icon
      ref="accountformRef"
    >
      <el-form-item label="帐号" prop="name">
        <el-input size="large" v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input size="large" v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
.panel-account {
}
</style>
